package com.peza.bikelog.common.json;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser.Feature;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.stereotype.Service;

@Service("jsonService")
public class JsonServiceImpl implements JsonService {

	private static ObjectMapper mapper;

	private static Logger logger = Logger.getLogger(JsonServiceImpl.class);

	public JsonServiceImpl() {
		mapper = new ObjectMapper();
	}

	@Override
	public <T> T fromJson(final String json, final TypeReference<T> type) {

		T data = null;

		try {
			data = mapper.readValue(json, type);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return data;
	}

	@Override
	public <T> T fromJson(final String json, final Class<T> type) {

		T data = null;

		try {
			data = mapper.readValue(json, type);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return data;
	}

	public <T> String toJson(T entry) {
		Writer writer = new StringWriter();
		try {
			mapper.writeValue(writer, entry);
			return writer.toString();
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;

	}

}
